

import 'dart:developer';

import 'package:cupertino_store/model/app_state_model.dart';
import 'package:cupertino_store/product_row_item.dart';
import 'package:cupertino_store/styles.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'search_bar.dart';

class SearchTab extends StatefulWidget {
  const SearchTab({super.key});

  @override
  State<StatefulWidget> createState() {
    return _SearchTabState();
  }
}


class _SearchTabState extends State <SearchTab>{
  late TextEditingController _textEditingController;
  late FocusNode _focusNode;
  String _terms = '';

  @override
  void initState() {
    super.initState();
    _textEditingController = TextEditingController()..addListener(_onTextChanged);
    _focusNode = FocusNode();
  }

  _onTextChanged(){
    setState(() {
      _terms = _textEditingController.text;
    });

    
  }

  @override
  void dispose() {
    super.dispose();
    _textEditingController.dispose();
    _focusNode.dispose();
  }

  @override
  Widget build(BuildContext context) {
    // return const CustomScrollView(
    //   slivers: [
    //     CupertinoSliverNavigationBar(
    //       largeTitle : Text('Search')
    //     ),
    //   ],
    // );

    log('_terms = $_terms');
    final model = Provider.of<AppStateModel>(context);
    final results = model.search(_terms);
    return DecoratedBox(
      decoration: const BoxDecoration(
        color: Styles.searchBackground
      ),
      child: SafeArea(
        child: Column(
          children: [
            _buildSearchBox(),
            Expanded(
              child: ListView.builder(
                itemBuilder: (context, index) => ProductRowItem(
                  product: results[index], 
                  index: index, 
                  lastItem:index == results.length - 1
                ),
                itemCount: results.length,
              )
            )
          ],
        ),
      ),
      );
  }
  
  Widget _buildSearchBox() {
    return Padding(
      padding: const EdgeInsets.all(8),
      child:  CustomSearchBar(
        controller: _textEditingController,
        focusNode: _focusNode,
      ),
    );
  }
}